package auth

import (
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/model"
	types2 "iot-base/auth/types"
)

type menuList []model.AuthRule

type menuItem struct {
	model.AuthRule
	Child []menuItem `json:"child"`
}

//GetSideBarList 获取无限级菜单
func GetSideBarList(c *gin.Context) {
	//requestId, _ := c.Get("RequestId")
	uid, _ := c.Get("uid")
	resp := types2.NewResult(c)
	logic := logic2.NewRulesLogic()
	list, err := logic.FindUserRule(uid.(int64))
	if err != nil {
		resp.ErrorCode(types2.DBError, err.Error())
		return
	}
	ml := menuList(list)
	ret := ml.processToTree(0, 0)
	resp.Success(ret)
}

func (m *menuList) processToTree(pid int64, level int64) []menuItem {
	var menuTree []menuItem
	if level == 10 {
		return menuTree
	}

	list := m.findChildren(pid)
	if len(list) == 0 {
		return menuTree
	}

	for _, v := range list {
		child := m.processToTree(v.ID, level+1)
		menuTree = append(menuTree, menuItem{v, child})
	}

	return menuTree
}

func (m *menuList) findChildren(pid int64) []model.AuthRule {
	var child []model.AuthRule
	for _, v := range *m {
		if v.Pid == pid {
			child = append(child, v)
		}
	}
	return child
}
